package com.star.batchhandler.demo;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;

import javax.sql.DataSource;

import com.star.platform.transaction.inter.ITransactionService;

public class TransactionJob extends AbstractJob{
	public static volatile int tJobs = 0;
	public TransactionJob(DataSource ds, ITransactionService tx) {
		super(ds, tx);
		tJobs++;
	}
	@Override
	public void run() {
		try {
			long begin = System.nanoTime();
			Connection conn = ds.getConnection();
			conn.setAutoCommit(false);
			
			Statement stmt = conn.createStatement();
			stmt.execute(getUpdateSQL());
			checkGT_1(stmt.getUpdateCount());
			stmt.close();
			System.out.println("update:[id=247]");
			
			stmt = conn.createStatement();
			checkRS1(stmt.executeQuery(selectSQL), "id");
			stmt.close();
			System.out.println("query:[id=247]");
			
			stmt = conn.createStatement();
			long id = getId(stmt.executeQuery(selectSEQ), "nextval");
			stmt.close();
			System.out.println("get sq of admin:[id=" + id + "]");
			
			PreparedStatement ps = conn.prepareStatement(getInsertSQL());
			ps.setLong(1, id);
			ps.execute();
			checkGT_1(ps.getUpdateCount());
			System.out.println("insert:[id=" + id + "]");
			ps.close();
			
			conn.commit();
			
			conn.close();
			synchronized (timeLock) {
				long time = System.nanoTime() - begin;
				tJobs--;
				System.out.println("this job consume time:" + time + " ns, left:"+tJobs);
				if(tJobs==0){
					System.out.println("$$$$$$$$$$$$$$$$$$\n" +
							"total consume time:" + (System.nanoTime()-SQLBatchOperation.begin)/(1000.0*1000) + " ms\n");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw new IllegalStateException("job exception!");
		}
	}
}
